package gvo.rero;


import gvo.importWindow.SearchResult;
import gvo.util.SearchParams;

import java.util.ArrayList;

import org.htmlparser.Parser;
import org.jdesktop.swingworker.SwingWorker;


public class ResultPage {
	private SearchParams searchParams;
	public ArrayList<SearchResult> rEntrys = new ArrayList<SearchResult>();
	//private LinkTag seite;
	//private int snr;
	public boolean isSearching = false;
	public boolean isFirstPage = false;
	public boolean isFilled = false;
	public Parser parser;
	private ReroSearch rs;
	private ResultPage resP;
	
	public ResultPage(SearchParams searchParams, ReroSearch rs) {
		
		this.searchParams = searchParams;
		isFirstPage = true;
		this.rs = rs;
		resP = this;
	}
	public void clear(){
		rEntrys.clear();
		isFilled = false;
	}
	public int getSNr() {
		return searchParams.seitenNr;
	}
	public void setSNr(int snr) {
		searchParams.seitenNr = snr;
	}
	public void setREntry(SearchResult entry) {
		entry.setLocation(searchParams.seitenNr, rEntrys.size());
		rEntrys.add(entry);
		
	}
	
	public void firstPage(SearchParams in){
		searchParams = in;
		isFirstPage = true;
		executeSearch();
	}
	public void otherPage(){
		isFirstPage = false;
		executeSearch();
	}
	public void executeSearch(){
		(new ParserWorker()).execute();
		
	}
	
	public String getSearchString() {
		return searchParams.url;
	}
	
	
	private class ParserWorker extends SwingWorker<Parser, Void> {
		@Override
		public Parser doInBackground() {
			isSearching = true;
			// Parser res;
			try {
				if(RDS.DEBUGINFO){
					System.out.println("START! " + isFirstPage);
				}
				rs.statusRI.setText("Suche ...  S."+ searchParams.seitenNr);
				if (isFirstPage) {
					if(RDS.DEBUGINFO){
						System.out.println("FirstPage");
					}
					parser = new Parser(searchParams.url);
				} else {
					if(RDS.DEBUGINFO){
						System.out.println("Other Page " + searchParams.url);
					}
					parser = new Parser(searchParams.url);

				}
			} catch (Exception e) {
				rs.statusRI.setText("Fehler bei (S. " + searchParams.seitenNr + "):"
						+ searchParams.url);
				e.printStackTrace();
				return null;
			}
			return parser;
		}

		@Override
		public void done() {
			isSearching = false;
			rs.internetImport.searchCompl = true; 
			rs.statusRI.setText("Fertig (S." + searchParams.seitenNr + ") " );
			if (parser == null) {
				rs.statusRI.setText("PANIC!");
			}
			if(rs.analyseParser(resP)){
				rs.statusRI.setText("Suchergebnis erhalten!");
			} else {
				rs.statusRI.setText("Kein Suchergebnis!");
			}

		}
	};
}
